/**
 * 用户表的使用
 */
import express from "express";
const user = express.Router();
import { dbContext } from "../../database/initialize.js";
import { guid, hash, compare } from "../../utils/utils.js";
// 登录
user.post("/login", async (req, res) => {
    try {
        const { userName, password } = req.body;
        if(!userName || !password) {
            return res.status(400).json({success: false, data: null, message: "账号和密码不能为空"});
        };
        if(password.length < 6) {
            return res.status(400).json({success: false, data: null, message: "密码必须至少 6 位"});
        };
        let queryField;
        if (/^\d{11}$/.test(userName)) {
            queryField = "USER_PHONE"; // 手机号登录
        } else if (/^[a-zA-Z0-9_]+$/.test(userName)) {
            queryField = "USER_ACCOUNT"; // 账号登录
        } else {
            queryField = "USER_NAME"; // 用户名登录
        };
        const stmt = dbContext.db.prepare(`SELECT USER_ID, USER_ACCOUNT, USER_NAME,USER_STATUS, USER_PASSWORD FROM fps_user WHERE ${queryField} = ? LIMIT 1`);
        stmt.bind([userName]);
        const user = stmt.step() ? stmt.getAsObject() : null;
        stmt.free();
        if(!user) {
            return res.status(200).json({success: false, data: user, message: "用户不存在！"});
        };
        const isMatch = await compare(password, user.USER_PASSWORD);
        if(!isMatch) {
            return res.status(200).json({success: false, data: null, message: "用户或密码错误！"});
        };
        if(Number(user.USER_STATUS) !== 1) {
            return res.status(200).json({success: false, data: null, message: "账号异常，请联系管理员"});
        };
        const token = guid();
        const now = new Date();
        const expiresAt = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000);
        const tokenStmt = dbContext.db.prepare(`INSERT INTO fps_sso_sessions (TOKEN_ID, USER_ID, TOKEN, CREATED_AT, EXPIRES_AT) VALUES (?, ?, ?, ?, ?)`);
        tokenStmt.bind([guid(), user.USER_ID, token, now.toISOString(), expiresAt.toISOString()]);
        tokenStmt.step();
        tokenStmt.free();
        const { USER_PASSWORD, ...userInfo } = user;
        res.status(200).json({success: true, data: {...userInfo, token}, message: "登录成功"});
    } catch (error) {
        console.error("/login 请求时发生错误：", error);
        res.status(500).json({success: false, data: error, message: "登录服务暂时不可用"})
    }
});

// 注册
user.post("/register", async (req, res) => {
    dbContext.db.exec("BEGIN TRANSACTION");
    try {
        const { userName, password } = req.body;
        if (!userName || !password) {
            dbContext.db.exec("ROLLBACK");
            return res.status(400).json({success: false,data: null,message: "用户名和密码不能为空"});
        };
        if (password.length < 6) {
            dbContext.db.exec("ROLLBACK");
            return res.status(400).json({success: false,data: null,message: "密码长度至少6位"});
        };
        const isPhone = /^\d{11}$/.test(userName);
        const isAccount = /^[a-zA-Z0-9_]+$/.test(userName);
        const checkStmt = dbContext.db.prepare(`SELECT USER_ID FROM fps_user WHERE USER_ACCOUNT = ? OR USER_PHONE = ? LIMIT 1`);
        checkStmt.bind([userName, isPhone ? userName : null]);
        if (checkStmt.step()) {
            checkStmt.free();
            dbContext.db.exec("ROLLBACK");
            return res.status(400).json({success: false,data:null,message: "该账号已存在"});
        };
        checkStmt.free();
        const insertStmt = dbContext.db.prepare(`INSERT INTO fps_user (USER_ID,USER_ACCOUNT,USER_NAME,USER_PHONE,USER_PASSWORD,CREATED_AT,UPDATED_AT) VALUES (?, ?, ?, ?, ?, ?, ?)`);
        const userId = guid();
        const now = new Date().toISOString();
        insertStmt.bind([userId, isAccount ? userName : null, (!isPhone && !isAccount) ? userName : null, isPhone ? userName : null, await hash(password),now,now]);
        insertStmt.step();
        insertStmt.free();
        dbContext.db.exec("COMMIT");
        res.status(200).json({success: true,data: { userId },message: "注册成功"});
    } catch (error) {
        dbContext.db.exec("ROLLBACK");
        console.error("/register 请求时发生错误：", error);
        res.status(500).json({success: false,data: error, message: "注册服务暂时不可用"});
    }
});

// 重置密码
user.post("/user/reset/password", async (req, res) => {
    dbContext.db.exec("BEGIN TRANSACTION");
    try {
        const { account, name, phone } = req.body;
        if(!account || !name || !phone) {
            dbContext.db.exec("ROLLBACK");
            return res.status(400).json({success: false,data: null,message: "账号、用户名、手机号均不能为空"});
        };
        const stmt = dbContext.db.prepare(`SELECT USER_ID, USER_ACCOUNT, USER_PHONE, USER_NAME FROM fps_user WHERE USER_ACCOUNT = ? AND USER_PHONE = ? AND USER_NAME = ? LIMIT 1`);
        stmt.bind([account, phone, name]);
        const user = stmt.step() ? stmt.getAsObject() : null;
        stmt.free();
        if(!user) {
            dbContext.db.exec("ROLLBACK");
            return res.status(404).json({success: false, data: null, message: "没有找到要重置密码的用户，请核对信息是否有误"});
        };
        const newPwd = "123456";
        const hasPwd = await hash(newPwd);
        const updatedAt = new Date().toISOString();
        const updateStmt = dbContext.db.prepare(`UPDATE fps_user SET USER_PASSWORD = ?, UPDATED_AT = ? WHERE USER_ID = ?`);
        updateStmt.bind([hasPwd, updatedAt, user.USER_ID]);
        updateStmt.step();
        updateStmt.free();
        const changes = dbContext.db.getRowsModified();
        if(changes === 0) {
            dbContext.db.exec("ROLLBACK");
            return res.status(500).json({success: false, data: null, message: "密码重置失败"});
        };
        dbContext.db.exec("ROLLBACK");
        res.status(200).json({success: true, data: { ...user, USER_PASSWORD: newPwd }, message: "密码已重置为默认值"});
    } catch (error) {
        dbContext.db.exec("ROLLBACK");
        console.error("/user/reset/password 请求时发生错误：", error);
        res.status(500).json({success: false,data: error, message: "重置密码服务暂时不能使用"});
    }
});

export default user;